//
//  MainViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/10/23.
//  Copyright © 2016年 com.rs. All rights reserved.
//

#import "MainViewController.h"
#import "HomeViewController.h"
#import "WeexViewController.h"
#import "MineViewController.h"
#import "WorkflowMenuListViewController.h"
#import "FunctionMenuListViewController.h"
#import "InformationMenuListViewController.h"
#import "UIImage+SuperCompress.h"

#import "LoginViewController.h"
#import "AppDelegate+Tip.h"
#import "MainViewController+TabViewController.h"
#import "MainViewController+FixedTab.h"

@interface MainViewController ()<CSessionOutDelegate>
{
    RSWDataOperation *_manager;
    NSMutableArray *_tabBarItems;
    NSMutableDictionary *_codeIndex;
    NSMutableArray *_qdData;
    
    BOOL _willLoginOut;
}
@end


@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initVariable];
    
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:@"observerMainViewControllerExitNotification:" forKey:MainViewControllerExitNotification];
    [dic setValue:@"observerHeadImageDownloadQueueHeadImageDownloadResultNotification:" forKey:XLGHeadImageDownloadQueueHeadImageDownloadResultNotification];
    [self addMainThreadObserverWithDictionarySelector:dic];
    [self addKeyboardObserver];
    
    //[_manager getMenuListCompletion:^(NSInteger nResult, NSArray *output, NSError *error) {
    //     [self requestComplete:nil result:nResult output:output error:error];
    // }];
    
    _tabBarItems = [self getTabItem];
    [self initUI];
    [self initService];
}

- (void)initVariable
{
    _tabBarItems = [NSMutableArray new];
    _codeIndex = [NSMutableDictionary new];
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
}

- (BOOL)tryWillLoginOut
{
    @synchronized(@"willLoginOut")
    {
        if(_willLoginOut == YES)
            return NO;
        _willLoginOut = YES;
        return YES;
    }
}

- (void)initService
{
    [XMSSingleQueue runSyncBlock:^
     {
         [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
         
         [RSWMessageOperation initRSWMessageOperation];
         
         [XLGUpdateSession initUpdateSessionTimer];
         
         if([XLGContext context].m_bIsofflinelogin == NO)
         {
             /*
             BOOL result = [RSWMessageOperation registerNotification];
             
             if(result == NO)
             {
                 [RSWMessageOperation bindPushAsyncCompletion:^(NSInteger nResult, BOOL bResult, NSError *error)
                  {
                      [RSWMessageOperation getChatOfflineMessage:YES complete:^(NSInteger nResult){ }];
                  }];
             }
              */
             
             [XLGUpdateSession resumeUpdateSessionTimer];
         }
         
         [XLGServiceTime startService];
         
         [XLGDownloadManager initDownloadManager];
         
         [XLGSendQueueManager initMultiSendQueueManagerWithKey:@[XLGSendQueueManagerDefaultKey,SendQueueExplicitKey] DBName:@[XLGSendQueueDefaultDBFile,SendQueueExplicitDBFile]];
         
         [[XLGSendQueueManager sendQueueManager] deleteAllFinishSendItemsAsyncCompletion:^{}];
         
         [[XLGSendQueueManager sendQueueManager:SendQueueExplicitKey] deleteSendIndex:^NSString *(NSString * condition)
          {
              if([condition isEqualToString:@"submittime"])
                  return [NSString stringWithFormat:@"submittime < %@",@((NSUInteger)[[NSDate date] timeIntervalSince1970] - 24 * 60 * 60 * 7 * 2)];
              return nil;
          } asyncCompletion:^{}];
         
         [[XMSNetWorkReachability reachability] startNotifier];
         
         [XMSBackgroundMaintain initBackgroundMaintain];
         [XMSBackgroundMaintain addBackgroundService:@{XLGSendQueueManagerBackgroundMaintainKey:[XLGSendQueueManager sendQueueManager:XLGSendQueueManagerDefaultKey],
                                                       SendQueueExplicitBackgroundMaintainKey:[XLGSendQueueManager sendQueueManager:SendQueueExplicitKey],
                                                       XLGDownloadManagerBackgroundMaintainKey:[XLGDownloadManager downloadManager]}];
     }];
    

    [CBMKMapManagerHelper start:[[NSBundle mainBundle] infoDictionary][@"BaiDuMapKey"]];
    
    [XLGHeadImageDownloadQueue initHeadImageDownloadQueue];
    
    NSString *path = [[XLGContext context].m_szUserdefaulteppath stringByAppendingPathComponent:HeadImageFolder];
    [XLGHeadImageDownloadQueue setLocalStorePath:path forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
    
    path = [[XLGContext context].m_szUserdefaulteppath stringByAppendingPathComponent:SysIconImageFolder];
    [XLGHeadImageDownloadQueue setLocalStorePath:path forKey:XLGHeadImageDownloadQueueSysIcon];
    
    [self viewDidLoadTabViewController];
    
    [XLGSessionOut sessionOutDelegate:self];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [self tabViewControllerWillDealloc];
    
    [_manager terminateRequest];
    
    [self removeObserver];
    
    [CBMKMapManagerHelper stop];
    
    [XLGHeadImageDownloadQueue clearTag:NSStringFromClass([self class]) forKey:XLGHeadImageDownloadQueueEntAddressBookContact];
    [XLGHeadImageDownloadQueue clearTag:NSStringFromClass([self class]) forKey:XLGHeadImageDownloadQueueSysIcon];
}

-(void)requestComplete:(XMSDataOperationManager *)dom result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                _qdData = output;
                
                 NSInteger tag = 0;
                for (MenuInfo *info in output)
                {
                    UIImage *headImage = nil;
                    if(info.icon.length >0)
                    {
                        if([info.icon rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
                        {
                            XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:info.icon forKey:XLGHeadImageDownloadQueueSysIcon];
                            if(cache != nil)
                                headImage = cache;
                            else
                                headImage = [UIImage imageNamed:@"img_defaulthead.png"];
                        }
                        else
                        {
                            NSString *h = [info.icon substringFromIndex:[info.icon rangeOfString:ServiceDefaultHeadImageTag].length];
                            headImage = [UIImage imageNamed:h];
                        }
                    }
                    else
                        headImage = [UIImage imageNamed:@"img_defaulthead.png"];
                    
                    headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(30, 30)];
                    UIImage *headImage_selected = [UIImage imageFromImage:headImage renderWithColor:[[UINavigationBar appearance] barTintColor]];
                    
                    XUITabBarItem *item = [[XUITabBarItem alloc] initWithTitle:info.name image:[headImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[headImage_selected imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] tag:tag];
                    
                    [_tabBarItems addObject:item];
                    
                    [_codeIndex setObject:info.code forKey:[NSString stringWithFormat:@"%@",@(tag)]];
                    
                    tag ++;
                }
                 
                [self initUI];
                break;
             }
             default:
             {
                break;
             }
         }
     }];
}

-(void)initUI{
    //[super viewDidLoad];
    
    [[XUINavigationController navigationController] setNavigationBarHidden:NO animated:YES];
    
    //修改bar选中以后字体颜色
    [[UITabBar appearance]setTintColor:[UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color]];
    
    self.tabBar.items = _tabBarItems;
    
    [self createDefaultIndexOfViewControllerClass];
}

//- (void)createViewControllerClassAtIndex:(NSUInteger)index block:(void (^)(Class cls, XUIViewControllerSwitchParam *param))block
//{
//    NSString *code = [_codeIndex valueForKey:[NSString stringWithFormat:@"%@",@(index)]];
//    if([code isEqualToString:@"ROOT_CHAT"])
//    {
//        block([InformationMenuListViewController class], nil);
//    }
//    else if([code isEqualToString:@"ROOT_MAIN"])
//    {
//        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
//        p.param[FunctionMenuListViewControllerMenuCodeParamKey] = code;
//        block([FunctionMenuListViewController class], p);
//    }
//    else if([code isEqualToString:@"ROOT_WORKFLOW"])
//    {
//        block([WorkflowMenuListViewController class],nil);
//    }
//    else if([code isEqualToString:@"ROOT_PERSONAL_CENTER"])
//    {
//        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
//        p.param[MineViewControllerMenuCodeParamKey] = code;
//
//        block([MineViewController class],p);
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- refresh headImage

-(void)observerHeadImageDownloadQueueHeadImageDownloadResultNotification:(NSNotification*)noti
{
    NSString *path =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    NSString *URL =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    
    NSInteger index = 0;
    for (MenuInfo *info in _qdData)
    {
        if([info.icon isEqualToString:URL])
        {
            index = [info.orderBy intValue];
            
            for(XUITabBarItem *item in self.tabBar.items)
            {
                if(item.tag == index)
                {
                    XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue setCacheWithHeadImageURL:URL andHeadImagePath:path forKey:XLGHeadImageDownloadQueueSysIcon];
                    
                    UIImage *headImage = (UIImage*)cache;
                    headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(30, 30)];
                    
                    item.image = [headImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                   
                    UIImage *headImage_selected = [UIImage imageFromImage:headImage renderWithColor:[[UINavigationBar appearance] barTintColor]];
                    item.selectedImage = [headImage_selected imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
                }
            }
        }
    }
}

#pragma --
#pragma exit

- (void)observerMainViewControllerExitNotification:(NSNotification *)noti
{
    if([self tryWillLoginOut] !=YES)
        return;
    
    [((AppDelegate*)[UIApplication sharedApplication].delegate) dissmissPresentViewController:YES];
    
    [self loginOut];
}

- (void)ObserverSessionTimeOut:(NSNotification *)noti
{
    if([self tryWillLoginOut] !=YES)
        return;
    
    [((AppDelegate*)[UIApplication sharedApplication].delegate) dissmissPresentViewController:YES];
    
    [XUIAlertView alertViewWithTitle:@"下线通知" message:@"您的登陆已过期" cancelButtonTitle:@"确定" otherButtonTitles:nil clickBlock:^(NSInteger nClickindex)
     {
         [self loginOut];
     }];
}

- (void)sessionOut
{
    if([self tryWillLoginOut] !=YES)
        return;
    
    [((AppDelegate*)[UIApplication sharedApplication].delegate) dissmissPresentViewController:YES];
    
    [XUIAlertView alertViewWithTitle:@"下线通知" message:@"您的帐号已经在其他设备登录" cancelButtonTitle:@"确定" otherButtonTitles:nil clickBlock:^(NSInteger nClickindex)
     {
         [self loginOut];
     }];
}

- (void)loginOut
{
    [AppDelegate presentCenterTipViewWithTip:@"注销中，请稍候" closeBlock:^(void(^f)())
     {
         [AppDelegate stopNetWorkChangeCheckTimer];
         
         [XMSSingleQueue runAsyncBlock:^
          {
              [self exit];
              
              f();
          }];
     }];
}


- (void)exit
{
    [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigDefaultKeyAutoLogin:@(0)}];
    
    [self exitService];
    
    DispatchMainThreadAsync(^
                            {
                                [XUINavigationController pushViewControllerClass:[LoginViewController class]];
                            });
}

- (void)exitService
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
    
    [[XMSNetWorkReachability reachability] stopNotifier];
    
    [XLGUpdateSession releaseUpdateSessionTimer];
    
    [RSWMessageOperation releaseRSWMessageOperation];
    
    [XLGDownloadManager releaseDownloadManager];
    
    [XLGSendQueueManager releaseSendQueueManager];
    
    [XLGServiceTime endService];
    
    [XMSBackgroundMaintain removeAllBackgroundService];
    [XMSBackgroundMaintain releaseBackgroundMaintain];
    
    [RSWDBOperation RSWDBOperationClose];
    
    [XLGHeadImageDownloadQueue releaseHeadImageDownloadQueue];
    
    [CRequestChannelPoolShell cancelRequestRequest];
    
    [XLGSessionOut sessionOutDelegate:nil];
    
    [CCurrentUser releaseCurrentUser];
    
    [XLGContext context].m_bLogined = NO;

    [XLGContext releaseContext];
    
    [CRequestChannelPoolShell stopRequestRunLoop];
}
@end
